package util

import (
	"encoding/base64"
	"fmt"
	"io/ioutil"
	"net/http"

	"github.com/DeanThompson/jpush-api-go-client"
	"github.com/DeanThompson/jpush-api-go-client/push"
)

const (
	appKey       = "532520c7edfe0af13e78d8fa"
	masterSecret = "087dc33e77959d64e2507351"
)

type pushAlert struct {
	Text       string
	RegisterId string
	Platform   string
}

var env = "dev"
var pushChn = make(chan pushAlert)
var httpClient = &http.Client{}

func InitPush(runmode string) {
	env = runmode
	go func() {
		for {
			doPush()
		}
	}()
}

func Push(text, registerId string, p string) {
	if env != "dev" {
		pushChn <- pushAlert{Text: text, RegisterId: registerId, Platform: p}
	}
}

func DeleteUser(userName string) (ok bool) {
	req, err := http.NewRequest("DELETE", fmt.Sprintf("https://api.im.jpush.cn/v1/users/%s", userName), nil)
	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("Authorization", fmt.Sprintf("Basic %s", base64.StdEncoding.EncodeToString([]byte(fmt.Sprintf("%s:%s", appKey, masterSecret)))))
	rsp, err := httpClient.Do(req)
	if rsp != nil && rsp.Body != nil {
		defer rsp.Body.Close()
	}
	if err != nil {
		GetLogger().Error("[util-push.DeleteUser] - error:%s", err.Error())
	} else {
		GetLogger().Info("jpush-DeleteUser. username:%s, statuscode:%d", userName, rsp.StatusCode)
		if rsp.StatusCode == 204 || rsp.StatusCode == 403 {
			ok = true
		} else {
			bts, _ := ioutil.ReadAll(rsp.Body)
			GetLogger().Error("[util-push.DeleteUser] - error:%d|%s", rsp.StatusCode, string(bts))
		}
	}

	return ok
}

func doPush() {
	entry := <-pushChn
	platform := push.NewPlatform()
	audience := push.NewAudience()
	audience.SetRegistrationId([]string{entry.RegisterId})
	notification := push.NewNotification("Golang.V3 Alert")
	client := jpush.NewJPushClient(appKey, masterSecret)
	options := push.NewOptions()
	if entry.Platform == Android_H5 {
		platform.Add("android")
		androidNotification := push.NewAndroidNotification(entry.Text)
		androidNotification.Title = "快来运消息推送通知"
		notification.Android = androidNotification
	} else {
		platform.Add("ios")
		iosNotification := push.NewIosNotification(entry.Text)
		iosNotification.Badge = 1
		notification.Ios = iosNotification
		options.ApnsProduction = true
	}

	options.TimeToLive = 86400
	payload := push.NewPushObject()
	payload.Platform = platform
	payload.Audience = audience
	payload.Notification = notification
	payload.Options = options
	if _, err := client.Push(payload); err != nil {
		GetLogger().Error("[util-push] - error:%s", err.Error())
	}

}
